import os
import traceback
import pandas as pd
import datetime
from xunkemgmt_client.tool.slack_noti import send_to_slack
from coin.base.mail_util import send_mail, send_mail_with_attachments
from absl import app, flags


def notice_slack(report, slack, subject, inconsistent_target_position):
  if slack is None:
    return
  send_to_slack(report, slack, 'file', subject)
  if inconsistent_target_position:
    send_to_slack("Inconsistent previous/target position. Please check", slack, 'msg', mention_list = ['wenge', "wliang", "tianqiang"])
     
     


def send_to_mail(report, from_mail, to_mail, subject, context):
  if to_mail is None:
    return
  try:
    send_mail_with_attachments("", from_mail, to_mail, subject, context, report)
  except:
    traceback.print_exc()

def check_target_position_usd(config_file_path, status_file_path):
    report = []
    symbols = []
    target_position_usds = []
    current_position_usds = []
    position_scale_factors = []
    position_distances = []
    target_position_diffs = []
    times = []
    data = pd.read_csv(config_file_path)
    config_target_position_usd = {}
    config_timestamp = {}
    symbol_unit_usd = {} 
    for index, row in data.iterrows():
        symbol = row["symbol"]
        config_target_position_usd[symbol] = float(row["target_position_usd"])
        config_timestamp[symbol] = int(row["timestamp"])
        symbol_unit_usd[symbol] = float(row["multiplier"]) * float(row["close"])
    data = pd.read_csv(status_file_path)
    for index, row in data.iterrows():
        symbol = row["symbol"]
        target_position_usd = float(row["target_position_usd"])
        current_position_usd = float(row["current_position_usd"])
        position_scale_factor = float(row["position_scale_factor"])
        scale_target_position_usd = target_position_usd * position_scale_factor
        position_distance_usd = abs(current_position_usd - scale_target_position_usd)
        timestamp = int(row["timestamp"])
        if symbol not in config_timestamp or timestamp < config_timestamp[symbol]:
           continue
        symbols.append(symbol)
        current_position_usds.append(current_position_usd)
        target_position_usds.append(target_position_usd)
        position_scale_factors.append(position_scale_factor)
        position_distances.append(round(position_distance_usd, 4))
        target_position_diffs.append(abs(config_target_position_usd[symbol] - target_position_usd))
        times.append(datetime.datetime.fromtimestamp(timestamp // 1e9))
    if len(symbols):
       report = [symbols, current_position_usds, target_position_usds, position_scale_factors, position_distances, target_position_diffs, times]
    return report
def main(argv):
  if flags.FLAGS.config_file_path == '' or flags.FLAGS.status_file_path == '':
    return
  report = check_target_position_usd(flags.FLAGS.config_file_path, flags.FLAGS.status_file_path)
  report_file = f'{flags.FLAGS.exchange}_position_exception_report.csv'
  if len(report) > 0:
    result = pd.DataFrame({
      'time' : report[6],
      'symbol' : report[0],
      'exchange' : flags.FLAGS.exchange,
      'target_position_usd' : report[2],
      'position_scale_factor' : report[3],
      'current_position_usd' : report[1],
      'position_distance_usd' : report[4],
      'target_position_diff' : report[5]})
    result.sort_values("position_distance_usd", ascending=False, inplace=True)
    #result["completion_rate"] = result["completion_rate"].map(lambda x: format(x,'.2%'))
    result.to_csv(report_file, index=False)
    status_path = flags.FLAGS.status_file_path.split('/')[-1].split('.')
    subject = status_path[0]+'.'+status_path[1]+'.'+status_path[2]
    notice_slack(result.to_string(index=False),
               flags.FLAGS.slack,
               subject,
               max(result["target_position_diff"]) > 1e-9)
    # send_to_mail(report_file,
    #            flags.FLAGS.from_mail,
    #            flags.FLAGS.to_mail,
    #            subject,
    #            f'{flags.FLAGS.exchange} Position Exception Report')


if __name__ == '__main__':
  flags.DEFINE_string('subject', '', 'email subject')
  flags.DEFINE_string('context', '', 'email context')
  flags.DEFINE_string('slack', None, 'slack_channel')
  flags.DEFINE_string('to_mail', None, 'to email address')
  flags.DEFINE_string('from_mail', 'no-reply@joomo.io', 'from email address')
  flags.DEFINE_string('config_file_path', '', 'config file path')
  flags.DEFINE_string('status_file_path', '', 'status file path')
  flags.DEFINE_string('exchange', '', 'exchange')
  app.run(main)